<?php

namespace app\admin\controller;

use think\facade\View;
use think\facade\Config;
use think\facade\Validate;
use think\facade\Db;
use app\admin\controller\Base;
use app\common\model\SystemMenu;
use app\common\model\SystemRole;
use app\common\model\User;
use app\common\model\SystemAdmin;
use think\facade\Filesystem;
use think\facade\Request;

class System extends Base
{
   
    // 权限管理-菜单管理
    public function menuList()
    {
        if (request()->IsAjax()) {
            // 查询权限
            $systemModel = new SystemMenu();
            $sort = 'sort ' . Config::get('sysconfig')['sort'];
            $menulist = $systemModel->getAllOrder([], '', $sort);
            return json(["code" => 0, "msg" => $systemModel->sysconfig['sort'], "count" => 20, "data" => $menulist]);
        } else {
            return View::fetch();
        }
    }
    // 权限管理-删除权限
    public function delMenu()
    {
        if (request()->IsAjax()) {
            $post = $this->request->post();
            if (isset($post['id']) && $post['id']) {
                try {
                    SystemMenu::destroy($post['id']);
                    // 删除子集
                    $systemModel = new SystemMenu();
                    $systemModel->destroyMenu($post['id']);
                    return json(['code' => 1, 'msg' => '删除成功']);
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json(['code' => 0, 'msg' => '删除失败']);
                }
            } else {
                return json(['code' => 0, 'msg' => '缺少参数']);
            }
        }
    }
    // 权限管理-修改权限
    public function editMenu()
    {
        // 查询顶级及其子类
        $get  = $this->request->get();
        if (isset($get['id']) && $get['id']) {
            $one =  SystemMenu::find($get['id']);
            $sysmenu = new SystemMenu;
            $menuList = $sysmenu->getMenu(0, 0);
            View::assign('one', $one);
            View::assign('menuList', $menuList);
            // var_dump($menuList);
            // die;
            return View::fetch();
        } else {
            return json(['code' => 0, 'msg' => '缺少参数']);
        }
    }

    // 权限管理-保存权限
    public function saveMenu()
    {
        if (request()->IsAjax()) {
            $post = $this->request->post();
            $addmenu = $post;
            // 状态
            if (isset($addmenu['status']) && $addmenu['status'] == 'on') {
                $addmenu['status'] = 1;
            } else {
                $addmenu['status'] = 0;
            }
            // 判断修改
            if (isset($addmenu['id']) && $addmenu['id']) {
                try {
                    SystemMenu::update($addmenu);
                    return json(['code' => 1, 'msg' => '更新成功']);
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json(['code' => 0, 'msg' => '新增失败']);
                }
            } else {
                // 新增
                try {
                    SystemMenu::create($addmenu);
                    return json(['code' => 1, 'msg' => '新增成功']);
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json(['code' => 0, 'msg' => '新增失败']);
                }
            }
        } else {
            // 查询顶级及其子类
            $menu = new SystemMenu;
            $menuList = $menu->getMenu(0, 0);
            View::assign('menuList', $menuList);
            return View::fetch();
        }
    }

    // 权限管理-角色列表
    public function roleList()
    {
        if (request()->IsAjax()) {
            // 查询权限
            $SystemRole = new SystemRole;
            $sort = 'sort ' . Config::get('sysconfig')['sort'];
            $list = $SystemRole->getAllOrder([], '', $sort);
            $count = $SystemRole->countRows([]);
            return json(["code" => 0, "msg" => '', "count" => $count, "data" => $list]);
        } else {
            return View::fetch();
        }
    }
    // 权限管理-保存角色
    public function saveRole()
    {
        if (request()->IsAjax()) {
            $post = $this->request->post();
            $addrole = $post;
            // 状态
            if (isset($addrole['status']) && $addrole['status'] == 'on') {
                $addrole['status'] = 1;
            } else {
                $addrole['status'] = 0;
            }
            // 判断修改
            if (isset($addrole['id']) && $addrole['id']) {
                try {
                    SystemRole::update($addrole);
                    return json(['code' => 1, 'msg' => '更新成功']);
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json(['code' => 0, 'msg' => '新增失败']);
                }
            } else {
                // 新增
                try {
                    SystemRole::create($addrole);
                    return json(['code' => 1, 'msg' => '新增成功']);
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json(['code' => 0, 'msg' => '新增失败']);
                }
            }
        } else {
            return View::fetch();
        }
    }
    // 权限管理-修改角色
    public function editRole()
    {
        $get  = $this->request->get();
        if (isset($get['id']) && $get['id']) {
            $one =  SystemRole::find($get['id']);
            View::assign('one', $one);
            return View::fetch();
        } else {
            return json(['code' => 0, 'msg' => '缺少参数']);
        }
    }
    // 权限管理-查询权限
    public function findRole()
    {
        if (request()->IsAjax()) {
            $post = $this->request->post();
            if (isset($post['id'])) {
                $one = SystemRole::find($post['id']);
                $power = explode(',', $one['power']);
                // 查询所有权限
                $sysmenu = new SystemMenu;
                $menuList = $sysmenu->getRole(0, $power);
                return json(['code' => 1, 'data' => $menuList]);
            } else {
                return json(['code' => 0, 'msg' => '缺少参数']);
            }
        }
    }

    // 权限管理-删除角色
    public function delRole()
    {
        if (request()->IsAjax()) {
            $post = $this->request->post();
            if (isset($post['id']) && $post['id']) {
                try {
                    SystemRole::destroy($post['id']);
                    return json(['code' => 1, 'msg' => '删除成功']);
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json(['code' => 0, 'msg' => '删除失败']);
                }
            } else {
                return json(['code' => 0, 'msg' => '缺少参数']);
            }
        }
    }
    // 权限管理-角色开关
    public function roleStatus()
    {
        if (request()->IsAjax()) {
            $post = $this->request->post();

            if (isset($post['id']) && $post['id']) {
                $save = [];
                $save['id'] = $post['id'];
                $save['status'] = $post['status'];
                try {
                    if ($save['status'] == 1) {
                        $str = '打开';
                    } else {
                        $str = '关闭';
                    }
                    SystemRole::update($save);
                    return json(['code' => 1, 'msg' => $str . '成功']);
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json(['code' => 0, 'msg' => $str . '失败']);
                }
            } else {
                return json(['code' => 0, 'msg' => '缺少参数']);
            }
        }
    }
    // 权限管理-管理员
    public function adminList()
    {
        if (request()->IsAjax()) {
            // 查询权限
            $get = $this->request->get();
            $limit = isset($get['limit']) && $get['limit'] ? $get['limit'] : 10;
            $page = isset($get['page']) && $get['page'] ? $get['page'] : 1;
            $SystemAdmin = new SystemAdmin;
            $sort = 'status desc,sort ' . Config::get('sysconfig')['sort'];
            $list = $SystemAdmin->getPagelist([], '', $sort, $limit, $page);
            $count = $SystemAdmin->countRows([]);
            $rolelist = SystemRole::where([])->column('name', 'id');
            foreach ($list as $k => $v) {
                $list[$k]['role_name'] = $rolelist[$v['role_id']] ?? '';
            }
            return json(["code" => 0, "msg" => '', "count" => $count, "data" => $list]);
        } else {
            return View::fetch();
        }
    }
    // 权限管理-添加管理员
    public function saveAdmin()
    {
        if (request()->IsAjax()) {
            $post = $this->request->post();
            $validate = Validate::rule([
                'admin|用户名' => 'require|min:5',
                'role_id|角色' => 'require|gt:0',
            ]);
            $validate->message([
                'admin.require' => '请填写用户名',
                'admin.max' => '用户名最短为5位',
                'role_id.require' => '请选择角色',
                'role_id.gt' => '请选择角色',
            ]);
            if (!$validate->check($post)) {
                return json(['code' => 0, 'msg' => $validate->getError()]);
            }
            $add_admin = $post;
            // 状态
            if (isset($add_admin['status']) && $add_admin['status'] == 'on') {
                $add_admin['status'] = 1;
            } else {
                $add_admin['status'] = 0;
            }
            unset($add_admin['is_supper']);
            // 判断修改
            if (isset($add_admin['id']) && $add_admin['id']) {
                try {
                    // 判断是否为超管
                    $thisAdmin = SystemAdmin::find($add_admin['id']);
                    if($thisAdmin['is_supper'] == 1){
                        $add_admin['role_id'] = 9999999999;
                        $add_admin['status'] = 1;
                    }
                    if (isset($add_admin['pwd1']) && trim($add_admin['pwd1'])) {
                        if (!isset($add_admin['pwd2']) || !trim($add_admin['pwd2'])) {
                            return json(['code' => 0, 'msg' => '请输入确认密码']);
                        }
                        if (trim($add_admin['pwd1']) != trim($add_admin['pwd2'])) {
                            return json(['code' => 0, 'msg' => '两次密码不一致']);
                        }
                        $add_admin['password'] = md5($add_admin['pwd1']);
                    }
                    unset($add_admin['admin']);
                    SystemAdmin::update($add_admin);
                    return json(['code' => 1, 'msg' => '更新成功']);
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json(['code' => 0, 'msg' => '新增失败']);
                }
            } else {
                // 新增
                try {
                    if (!isset($add_admin['pwd1']) || !trim($add_admin['pwd1'])) {
                        return json(['code' => 0, 'msg' => '请输入密码']);
                    }
                    if (!isset($add_admin['pwd2']) || !trim($add_admin['pwd2'])) {
                        return json(['code' => 0, 'msg' => '请输入确认密码']);
                    }
                    if (trim($add_admin['pwd1']) != trim($add_admin['pwd2'])) {
                        return json(['code' => 0, 'msg' => '两次密码不一致']);
                    }
                    // 判断是否含有
                    if (SystemAdmin::where(['admin' => $add_admin['admin']])->count()) {
                        return json(['code' => 0, 'msg' => '当前用户名已占用']);
                    }
                    $add_admin['password'] = md5($add_admin['pwd1']);
                    $add_admin['add_time'] = time();
                    SystemAdmin::create($add_admin);
                    return json(['code' => 1, 'msg' => '新增成功']);
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json(['code' => 0, 'msg' => '新增失败']);
                }
            }
        } else {
            $SystemRole = new SystemRole;
            $sort = 'sort ' . Config::get('sysconfig')['sort'];
            $list = $SystemRole->getAllOrder(['status' => 1], '', $sort)->toArray();
            View::assign('roleList', $list);
            return View::fetch();
        }
    }

    // 权限管理-删除管理员
    public function delAdmin()
    {
        if (request()->IsAjax()) {
            $post = $this->request->post();
            if (isset($post['id']) && $post['id']) {
                // 判断管理是否为超级管理
                $thisAdmin = SystemAdmin::find($post['id']);
                if($thisAdmin['is_supper'] == 1){
                    return json(['code' => 0, 'msg' => '请不要花样作死']);
                }
                try {
                    SystemAdmin::destroy($post['id']);
                    return json(['code' => 1, 'msg' => '删除成功']);
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json(['code' => 0, 'msg' => '删除失败']);
                }
            } else {
                return json(['code' => 0, 'msg' => '缺少参数']);
            }
        }
    }
    // 权限管理-更新状态
    public function adminStatus()
    {
        if (request()->IsAjax()) {
            $post = $this->request->post();
            if (isset($post['id']) && $post['id']) {
                $save = [];
                $save['id'] = $post['id'];
                $save['status'] = $post['status'];
                try {
                    if ($save['status'] == 1) {
                        $str = '打开';
                    } else {
                        $str = '关闭';
                    }
                    SystemAdmin::update($save);
                    return json(['code' => 1, 'msg' => $str . '成功']);
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json(['code' => 0, 'msg' => $str . '失败']);
                }
            } else {
                return json(['code' => 0, 'msg' => '缺少参数']);
            }
        }
    }
    // 权限管理-修改管理员
    public function editAdmin()
    {
        $get  = $this->request->get();
        if (isset($get['id']) && $get['id']) {
            $one =  SystemAdmin::find($get['id']);
            $SystemRole = new SystemRole;
            $user = new User;
            $sort = 'sort ' . Config::get('sysconfig')['sort'];
            $list = $SystemRole->getAllOrder(['status' => 1], '', $sort)->toArray();
            $userList = $user->getAll([])->toArray();
            View::assign('roleList', $list);
            View::assign('userList', $userList);
            View::assign('one', $one);
            return View::fetch();
        } else {
            return json(['code' => 0, 'msg' => '缺少参数']);
        }
    }
    // 权限管理-上传logo
    public function uploadLogo(){
        $file = request()->file('file');
        if (!$file) {
            return ['status' => 0, 'msg' => '上传失败，name不存在'];
        }
        $logoName = "adminLogo.".$file->getOriginalExtension();
        $savename = Filesystem::disk('system')->putFileAs("", $file,$logoName);
        if ($savename) {
            // $saveArr = explode('.',$savename);
            return ['status'=>1,'msg'=>'上传成功','fileName'=>$logoName];
        } else {
            return ['status'=>0,'msg'=>'上传失败'];
        }
    }
    // 权限管理-上传ico
    public function uploadIco(){
        $file = request()->file('file');
        if (!$file) {
            return ['status' => 0, 'msg' => '上传失败，name不存在'];
        }
        // $logoName = "adminLogo.".$file->getOriginalExtension();
        $savename = Filesystem::disk('system')->putFileAs("", $file,'favicon.ico');
        if ($savename) {
            // $saveArr = explode('.',$savename);
            return ['status'=>1,'msg'=>'上传成功','fileName'=>'favicon.ico'];
        } else {
            return ['status'=>0,'msg'=>'上传失败'];
        }
    }
    // 权限管理-系统设置
    public function systemConfig()
    {
        if (request()->IsAjax()) {
            $post = $this->request->post();
            $data = Config::get('sysconfig');
            foreach ($post as $k => $v) {
                $data[$k] = $v;
            }
            $str = "<?php \n\nreturn [";
            foreach ($data as $k => $v) {
                $str .= "\n    '" . $k . "'=>'" . $v . "',";
            }
            $str .= "\n];";
            $res = file_put_contents(CONF_PATH . 'sysconfig.php', $str);
            return json(['code' => 1, 'msg' => '保存成功']);
        }
        $one = Config::get('sysconfig');
        View::assign('one', $one);
        return View::fetch();
    }


    // 账号密码
    public function accountPass()
    {
        $get  = $this->request->get();
            $one =  SystemAdmin::find(7);
            View::assign('one', $one);
            return View::fetch();
     
    }

    // 账号密码修改
    public function savePass()
    {
      
        $post = $this->request->post();

        if(empty($post['admin'])){
            return json(['code' => 0, 'msg' => '请输入账号']);
        }

        if(empty($post['new_pass'])){
            return json(['code' => 0, 'msg' => '请输入新密码']);
        }

        if(empty($post['next_pass'])){
            return json(['code' => 0, 'msg' => '请输入再次输入密码密码']);
        }

        if($post['new_pass'] != $post['next_pass']){
            return json(['code' => 0, 'msg' => '两次密码不一致']);
        }

        $save['admin'] = $post['admin'];
        $save['password'] = md5(trim($post['new_pass']));
        
        try {
            SystemAdmin::where(["id"=>7])->update($save);
            return json(['code' => 1, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            return json(['code' => 0, 'msg' => '新增失败']);
        }
         
    }
}
